package com.yyk.yiliao.ui.trade;

import android.os.Bundle;
import android.os.CountDownTimer;
import androidx.appcompat.app.AlertDialog;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.aa.OnClickFlagUtil;
import com.yyk.yiliao.util.BtnToEditListenerUtil;
import com.yyk.yiliao.util.DialogUtil;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.glide.GlideUtils;
import com.yyk.yiliao.util.pay.PayUtils;
import com.yyk.yiliao.util.pay.PayUtils2;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.bean.OrderCheckcodeInfo;
import com.yyk.yiliao.bean.OrderGetchargeInfo;
import com.yyk.yiliao.bean.OrderPaysmsInfo;
import com.yyk.yiliao.bean.OrderRechargeInfo;
import com.yyk.yiliao.bean.OrderRecmoneyInfo;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.bean.WechatUnifiedorder_Info;

import java.text.DecimalFormat;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 充值
 */
public class RechargeActivity extends BaseActivity {
    public static RechargeActivity intanse;
    @BindView(R.id.et_money) //输入金额
            EditText etMoney;
    @BindView(R.id.ll_xzyh)
    LinearLayout llXzyh;
    @BindView(R.id.ll_payfangshi)
    LinearLayout llPayfangshi;
    @BindView(R.id.bt_next)
    Button btNext;
    @BindView(R.id.iv_img) // 银行图标
            ImageView ivImg;
    @BindView(R.id.tv_cardtype_name)//银行名字
            TextView tvCardtypeName;
    @BindView(R.id.iv_wxzfb)
    ImageView ivWxzfb;
    @BindView(R.id.tv_wxzfb)
    TextView tvWxzfb;
    @BindView(R.id.ll_wxzfbpay)
    LinearLayout llWxzfbpay;
    @BindView(R.id.tv_moneymessage) //金额提示
            TextView tvMoneymessage;
    private String cardId = null; //银行ID
    private float max; //充值最大金额
    private float min;//充值最小金额

    @Override
    public int getLayoutId() {
        return R.layout.activity_recharge;
    }

    @Override
    public void initView() {
        initToolbar();
        initEdittext();
        initButton();


    }

    private void initButton() {
        BtnToEditListenerUtil.getInstance().setBtn(btNext).setBackgroud(R.color.blue_51, R.color.blue_89)
                .addEditView(etMoney)
                .build();
    }

    private int length;

    private void initEdittext() {
        InputFilter[] filters = {new CashierInputFilter()};
        etMoney.setFilters(filters);

        etMoney.addTextChangedListener(new TextWatcher() {
            private float moneyFloat; //输入多少钱
            private String moneyString;
            DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
//                                String distanceString = decimalFormat.format(distanceValue) //format 返回的是字符串

            //之前
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            //中间
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                length = s.length();
                if (length != 0) {
                    moneyString = String.valueOf(s);
                    moneyFloat = Float.valueOf(moneyString);
                    if (moneyFloat < min) {
                        tvMoneymessage.setVisibility(View.VISIBLE);
                        tvMoneymessage.setText("充值最小金额 " + min + "元");
                    } else if (moneyFloat > max) {
                        tvMoneymessage.setVisibility(View.VISIBLE);
                        tvMoneymessage.setText("充值最大金额 " + max + "元");
                    } else {
                        tvMoneymessage.setVisibility(View.GONE);
                    }
                } else {
                    tvMoneymessage.setVisibility(View.GONE);
                }


            }

            //之后
            @Override
            public void afterTextChanged(Editable s) {


            }


        });
    }

    private void initToolbar() {
        setBackArrow();
        setTitle("充值");
    }


    @Override
    public void initData() {
        intanse = this;
        initS();
    }

    private void initS() {
        Map<String, String> map = new TreeMap<>();
        map.put("type_user", "1");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postOrderGetcharge(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new Subscriber<OrderGetchargeInfo>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtil.showShort(mActivity, "异常" + e.getMessage());

                    }

                    @Override
                    public void onNext(OrderGetchargeInfo info) {
                        //正确输入不打印出来值
                        Logger.e("充值提示" + info.toString());
                        if (info.getCode() == 1) {
                            OrderGetchargeInfo.DataBean data = info.getData();
                            max = data.getMax();
                            min = data.getMin();
                        }
                    }
                });
    }

    /**
     * 默认为活动支付
     * cardId=1 支付宝
     * cardId=2 微信
     * <p>
     * 其他是活动支付
     */
    private void goToNext() {
        Bundle bundle;
        if (cardId.equals("1")) {
            bundle = new Bundle();
            bundle.putString("money", etMoney.getText().toString().trim() + "");
            bundle.putString("payflag", "充值成功");
            startAct(PayMoneySuccendActivity.class, bundle);
        } else if (cardId.equals("2")) {
            bundle = new Bundle();
            bundle.putString("payflag", "充值成功");
            bundle.putString("money", etMoney.getText().toString().trim() + "");
            startAct(PayMoneySuccendActivity.class, bundle);
        }

    }

    /**
     * 1.选择银行支付方式
     * 2.手机验证码
     *
     * @param view
     */
    private String banktel; //银行预留手机号码

    @OnClick({R.id.ll_xzyh, R.id.ll_wxzfbpay, R.id.ll_payfangshi, R.id.bt_next})
    public void onViewClicked(View view) {
        if (OnClickFlagUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.ll_xzyh:
                DialogUtil.getIntanse().showPayFangshiDialog(mActivity, true, false, new DialogUtil.SelectPayListenter() {
                    @Override
                    public void onClick(String img, String name, String id, String phone, AlertDialog dialog) {
                        llPayfangshi.setVisibility(View.GONE);
                        cardId = id;
                        if (name.equals("微信支付") || name.equals("支付宝支付")) {
                            llXzyh.setVisibility(View.GONE);
                            llWxzfbpay.setVisibility(View.VISIBLE);
                            tvWxzfb.setText(name);
                            ivWxzfb.setImageResource(Integer.valueOf(img));

//                            GlideUtils.loadImage(mActivity, img, ivWxzfb);
                        } else {
                            llXzyh.setVisibility(View.VISIBLE);
                            llWxzfbpay.setVisibility(View.GONE);
                            banktel = phone;

                            GlideUtils.loadImage(mActivity, ApiService.BASE_URL + img, ivImg);
                            tvCardtypeName.setText(name);
                        }
                        dialog.dismiss();
                    }
                });
                break;
            case R.id.ll_wxzfbpay:
                DialogUtil.getIntanse().showPayFangshiDialog(mActivity, true, false, new DialogUtil.SelectPayListenter() {
                    @Override
                    public void onClick(String img, String name, String id, String phone, AlertDialog dialog) {
                        llPayfangshi.setVisibility(View.GONE);
                        cardId = id;
                        if (name.equals("微信支付") || name.equals("支付宝支付")) {
                            llXzyh.setVisibility(View.GONE);
                            llWxzfbpay.setVisibility(View.VISIBLE);
                            tvWxzfb.setText(name);
                            ivWxzfb.setImageResource(Integer.valueOf(img));

//                            GlideUtils.loadImage(mActivity, Integer.valueOf(img), ivWxzfb);

                        } else {
                            llXzyh.setVisibility(View.VISIBLE);
                            llWxzfbpay.setVisibility(View.GONE);
                            banktel = phone;

                            GlideUtils.loadImage(mActivity, ApiService.BASE_URL + img, ivImg);
                            tvCardtypeName.setText(name);
                        }
                        dialog.dismiss();
                    }
                });
                break;
            case R.id.ll_payfangshi:
                DialogUtil.getIntanse().showPayFangshiDialog(mActivity, true, false, new DialogUtil.SelectPayListenter() {


                    @Override
                    public void onClick(String img, String name, String id, String phone, AlertDialog dialog) {
                        llPayfangshi.setVisibility(View.GONE);
                        cardId = id;
                        if (name.equals("微信支付") || name.equals("支付宝支付")) {
                            llXzyh.setVisibility(View.GONE);
                            llWxzfbpay.setVisibility(View.VISIBLE);
                            tvWxzfb.setText(name);
                            ivWxzfb.setImageResource(Integer.valueOf(img));
//                            GlideUtils.loadImage(mActivity, Integer.valueOf(img), ivWxzfb);

                        } else {
                            llXzyh.setVisibility(View.VISIBLE);
                            llWxzfbpay.setVisibility(View.GONE);
                            banktel = phone;
                            GlideUtils.loadImage(mActivity, ApiService.BASE_URL + img, ivImg);
                            tvCardtypeName.setText(name);
                        }
                        dialog.dismiss();

                    }
                });
                break;
            case R.id.bt_next:
                String etmoney = etMoney.getText().toString().trim();
                if (TextUtils.isEmpty(cardId)) {
                    ToastUtil.showShort(mActivity, "请选择充值方式");
                    return;
                }
                if (cardId != null)
                    switch (cardId) {
                        //支付宝
                        case "1":
                            Map<String, String> map = new TreeMap<>();
                            map.put("id", Hawk.get("uid") + "");
                            map.put("utype", "1");
                            map.put("money", etmoney + "");
                            map.put("sign", Md5Util2.createSign(map));
                            RxUtils.getInstance().retrofit.create(ApiService.class).postOrderRecharge(map)
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .unsubscribeOn(Schedulers.io())
                                    .subscribe(new Subscriber<OrderRechargeInfo>() {
                                        @Override
                                        public void onCompleted() {

                                        }

                                        @Override
                                        public void onError(Throwable e) {

                                        }

                                        @Override
                                        public void onNext(OrderRechargeInfo info) {
                                            Logger.e("充值 暂时有支付宝" + info.toString());
                                            if (info.getCode() == 1) {
                                                String order_code = info.getData().getOrder_code();

                                                PayUtils instance = PayUtils.getInstance(mActivity);
                                                instance.setAlipayBack(new PayUtils.AlipayBack() {
                                                    @Override
                                                    public void payBack(boolean status) {
                                                        if (status) {
                                                            goToNext();
                                                        }
                                                    }
                                                });
                                                instance.payV2(Float.parseFloat(etmoney), order_code);
                                            } else {
                                                ToastUtil.showShort(mActivity, "交易失败");
                                            }
                                        }
                                    });

                            break;
                        //微信
                        case "2":

                            Map<String, String> wxMap = new TreeMap<>();
                            wxMap.put("id", Hawk.get("uid") + "");
                            wxMap.put("utype", "1");
                            wxMap.put("money", etmoney + "");
                            wxMap.put("sign", Md5Util2.createSign(wxMap));
                            RxUtils.getInstance().retrofit.create(ApiService.class).
                                    postOrderRecharge(wxMap)
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .unsubscribeOn(Schedulers.io())
                                    .subscribe(new Subscriber<OrderRechargeInfo>() {


                                        @Override
                                        public void onCompleted() {

                                        }

                                        @Override
                                        public void onError(Throwable e) {

                                        }

                                        @Override
                                        public void onNext(OrderRechargeInfo info) {
                                            Logger.e("充值 暂时有微信" + info.toString());
                                            if (info.getCode() == 1) {
                                                String order_code = info.getData().getOrder_code();
                                                Map<String, String> map = new TreeMap<>();
                                                map.put("order_code", order_code);
                                                map.put("sign", Md5Util2.createSign(map));
                                                RxUtils.getInstance().retrofit.create(ApiService.class).postWechatUnifiedorder(map)
                                                        .subscribeOn(Schedulers.io())     //调度线程
                                                        .observeOn(AndroidSchedulers.mainThread())
                                                        .unsubscribeOn(Schedulers.io())   //取消订阅
                                                        .subscribe(new Subscriber<WechatUnifiedorder_Info>() {
                                                            @Override
                                                            public void onCompleted() {
                                                                //完成的时候调用
                                                            }

                                                            @Override
                                                            public void onError(Throwable e) {
                                                                e.printStackTrace();
                                                            }

                                                            @Override
                                                            public void onNext(WechatUnifiedorder_Info info) {
                                                                Logger.e("  微信返回值" + info.toString());
                                                                if (info.getCode() == 1) {
                                                                    PayUtils2 instance = PayUtils2.getInstance(mActivity);
                                                                    instance.setWxBack(new PayUtils2.WXBack() {
                                                                        @Override
                                                                        public void payBack(boolean status) {
                                                                            if (status) {
                                                                                goToNext();
                                                                            }
                                                                        }
                                                                    });
                                                                    instance.invokeWxPay(info);
                                                                }
                                                            }
                                                        });
                                            } else {
                                                ToastUtil.showShort(mActivity, "交易失败");
                                            }
                                        }
                                    });

                            break;

                        default:
                            Map<String, String> smsMap = new TreeMap<>();
                            smsMap.put("id", Hawk.get("uid") + "");
                            smsMap.put("type_user", "1");
                            smsMap.put("money", etmoney + "");
                            smsMap.put("cardid", cardId + "");
                            smsMap.put("sign", Md5Util2.createSign(smsMap));
                            RxUtils.getInstance().retrofit.create(ApiService.class).postOrderRecmoney(smsMap)
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .unsubscribeOn(Schedulers.io())
                                    .subscribe(new Subscriber<OrderRecmoneyInfo>() {
                                        @Override
                                        public void onCompleted() {

                                        }

                                        @Override
                                        public void onError(Throwable e) {

                                        }

                                        @Override
                                        public void onNext(OrderRecmoneyInfo info) {
                                            Logger.e("充值 银行" + info.toString());
                                            if (info.getCode() == 1) {
                                                String order_code = info.getData().getOrder_code();
                                                String token = info.getData().getToken();

                                                DialogUtil.getIntanse().showPhoneSmsDialog(mActivity, new DialogUtil.RechargeListenter() {
                                                    @Override
                                                    public void onClick(String password, AlertDialog dialog) {
                                                        Map<String, String> map = new TreeMap<>();
                                                        map.put("token", token);
                                                        map.put("code", password + "");
                                                        map.put("order_code", order_code);
                                                        map.put("sign", Md5Util2.createSign(map));
                                                        RxUtils.getInstance().retrofit.create(ApiService.class).postOrderCheckcode(map)
                                                                .subscribeOn(Schedulers.io())
                                                                .observeOn(AndroidSchedulers.mainThread())
                                                                .unsubscribeOn(Schedulers.io())
                                                                .subscribe(new Subscriber<OrderCheckcodeInfo>() {
                                                                    @Override
                                                                    public void onCompleted() {

                                                                    }

                                                                    @Override
                                                                    public void onError(Throwable e) {

                                                                    }

                                                                    @Override
                                                                    public void onNext(OrderCheckcodeInfo info) {
                                                                        Logger.e("接口22：验证支付短信（ggk" + info.toString());
                                                                        if (info.getCode() == 1) {
                                                                            Bundle bundle = new Bundle();
                                                                            bundle.putString("money", etmoney);
                                                                            bundle.putString("payflag", "充值成功");
                                                                            startAct(PayMoneySuccendActivity.class, true, bundle);
                                                                            dialog.dismiss();
                                                                        } else {
                                                                            ToastUtil.showShort(mActivity, info.getMsg());
                                                                        }
                                                                    }
                                                                });


                                                    }

                                                    @Override
                                                    public void onTextPhone(TextView textView, TextView
                                                            textView2) {
                                                        textView.setText(banktel);
                                                        timeCount = new TimeCount(60000, 1000, textView2);
                                                        timeCount.start();
                                                    }


                                                    @Override
                                                    public void postHttp() {

                                                    }

                                                    @Override
                                                    public void sendSms(TextView sms) {
                                                        Map<String, String> map = new TreeMap<>();
                                                        map.put("token", token);
                                                        map.put("sign", Md5Util2.createSign(map));
                                                        RxUtils.getInstance().retrofit.create(ApiService.class).postOrderPaysms(map)
                                                                .subscribeOn(Schedulers.io())
                                                                .observeOn(AndroidSchedulers.mainThread())
                                                                .unsubscribeOn(Schedulers.io())
                                                                .subscribe(new Subscriber<OrderPaysmsInfo>() {
                                                                    @Override
                                                                    public void onCompleted() {

                                                                    }

                                                                    @Override
                                                                    public void onError(Throwable e) {

                                                                    }

                                                                    @Override
                                                                    public void onNext(OrderPaysmsInfo info) {
                                                                        Logger.e("接口23：重发支付短信" + info.toString());
                                                                        if (info.getCode() == 1) {
                                                                            ToastUtil.showShort(mActivity, "获取验证码");
                                                                            timeCount = new TimeCount(60000, 1000, sms);
                                                                            timeCount.start();
                                                                        } else {
                                                                            ToastUtil.showShort(mActivity, info.getMsg());
                                                                        }
                                                                    }
                                                                });
                                                    }


                                                });

                                            } else if (info.getCode() == 99) {
                                            } else {
                                                ToastUtil.showShort(mActivity, info.getMsg());
                                            }
                                        }
                                    });


                            break;

                    }


                break;
        }
    }

    /**
     * 发送验证码
     */
    private TimeCount timeCount;


    /**
     * 设置 60秒时间 倒计时
     */
    private class TimeCount extends CountDownTimer {
        private TextView tvSendsms;

        public TimeCount(long millisInFuture, long countDownInterval, TextView tvSendsms) {
            super(millisInFuture, countDownInterval);
            this.tvSendsms = tvSendsms;
        }

        @Override
        public void onTick(long millisUntilFinished) {
//            mLoginEdit.setBackgroundColor(Color.parseColor("#B6B6D8"));
            tvSendsms.setClickable(false);
            tvSendsms.setText(millisUntilFinished / 1000 + "s后重发");
            tvSendsms.setTextColor(getResources().getColor(R.color.gray_c1));

        }

        @Override
        public void onFinish() {
            tvSendsms.setClickable(true);
            tvSendsms.setText("获取验证码");
            tvSendsms.setTextColor(getResources().getColor(R.color.gray_c1));

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timeCount != null) {
            timeCount.cancel();
        }
    }
}
